package com.multicampus.sample.lucene;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;

public class FileSystemIndexer {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		if (args.length != 1) {
			System.out
					.println("java com.multicampus.sample.lucene.FileSystemIndexer directory_name");
			System.exit(1);
		}

		try {
			IndexWriter writer = new IndexWriter("/data/index/filesystem",
					new CJKAnalyzer(), true);
			System.out.println("Usage:Indexing to directory '" + args[0]
					+ "'...");

			indexDocs(writer, new File(args[0]));

			System.out.println("Optimizing...");
			writer.optimize();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public static void indexDocs(IndexWriter writer, File file)
			throws IOException {
		// do not try to index files that cannot be read
		if (file.canRead()) {
			if (file.isDirectory()) {
				String[] files = file.list();
				// an IO error could occur
				if (files != null) {
					for (int i = 0; i < files.length; i++) {
						indexDocs(writer, new File(file, files[i]));
					}
				}
			} else {
				System.out.println("adding " + file);

				try {
					Document doc = new Document();
					doc.add(new Field("path", file.getPath(), Field.Store.YES,
							Field.Index.UN_TOKENIZED));
					doc.add(new Field("modified", DateTools.timeToString(file
							.lastModified(), DateTools.Resolution.MINUTE),
							Field.Store.YES, Field.Index.UN_TOKENIZED));
					doc.add(new Field("title", file.getName(), Field.Store.YES,
							Field.Index.UN_TOKENIZED));
					doc.add(new Field("contents", new FileReader(file)));

					writer.addDocument(doc);
				} catch (FileNotFoundException fnfe) {
					;
				}
			}
		}
	}
}
